package Servlet;

import Dao.BaseDao;
import Dao.UserDao;
import Service.UserService;
import bean.customer;
import javafx.application.Application;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = "/LoginServlet")
public class LoginServlet extends BaseServlet {

    protected void login(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //1.获取请求参数
        UserDao userDao = new UserDao();
      String account =  req.getParameter("phonenumber");
      String password = req.getParameter("password");
        customer Logincustomer = new customer(null,null,account,password);
        UserService userService = new UserService();


        if(userService.login(Logincustomer)!=null){


            //设置cookie，回显用户数据
            Integer id = userDao.queryIdByPhoneNumberAndPassword(account,password);
            Cookie CookieId = new Cookie("id",id.toString());
            CookieId.setMaxAge(60*60*24*365);
            resp.addCookie(CookieId);

            Cookie CookiePhoneNumber = new Cookie("phoneNumber",account);
            CookiePhoneNumber.setMaxAge(60*60*24*365);
            resp.addCookie(CookiePhoneNumber);

            Cookie CookiePassWord = new Cookie("password",password);
            CookiePassWord.setMaxAge(60*60*24*365);
            resp.addCookie(CookiePassWord);

           String name = userDao.queryNameByPhoneNumberAndPassword(account,password);
           Cookie cookieName = new Cookie("name",name);
           cookieName.setMaxAge(60*60*24*365);
           resp.addCookie(cookieName);

           req.getRequestDispatcher("/index.jsp").forward(req,resp);
        }

        else {
                req.setAttribute("message","账号或密码不正确");
                req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }

    }
    protected void manger_login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取请求参数
        req.setCharacterEncoding("UTF-8");
        String phonenumber = req.getParameter("phonenumber");
        String password = req.getParameter("password");

        if(phonenumber.equals("sa")&&password.equals("123456")){
            req.getRequestDispatcher("/manger_homepage.jsp").forward(req,resp);
        }
        else{
            req.setAttribute("message","管理员账号或密码不正确");
            req.getRequestDispatcher("/manger_login.jsp").forward(req,resp);
        }

    }
}

